package us.mooresr.aircraftscheduling.client.ui;

import us.mooresr.aircraftscheduling.client.AdminGatekeeper;
import us.mooresr.aircraftscheduling.client.LoginStateManager;
import us.mooresr.aircraftscheduling.client.events.UserLoggedOutEvent;
import us.mooresr.aircraftscheduling.client.place.NameTokens;

import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ContentSlot;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.Proxy;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;
import com.google.inject.Inject;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.gwtplatform.mvp.client.proxy.RevealRootContentEvent;

public class MainPagePresenter extends
		Presenter<MainPagePresenter.MyView, MainPagePresenter.MyProxy>
		implements MainPageUiHandlers {
	
	private final LoginStateManager loginStateManager;
	private final PlaceManager placeManager;
	
	@ContentSlot
	public static final Type<RevealContentHandler<?>> TYPE_SetMainContent = new Type<RevealContentHandler<?>>();

	public interface MyView extends View {
		void revealAdminFunctions(Boolean b);
		void setUsername(String currentUserName);
		void setPresenter(MainPagePresenter mainPagePresenter);
	}

	@ProxyStandard
	public interface MyProxy extends Proxy<MainPagePresenter> {
	}

	@Inject
	public MainPagePresenter(final EventBus eventBus, final MyView view,
			final MyProxy proxy, final LoginStateManager loginStateManager,
			final PlaceManager placeManager) {
		super(eventBus, view, proxy);
		this.loginStateManager = loginStateManager;
		this.placeManager = placeManager;
		getView().setPresenter(this);
	}

	@Override
	protected void revealInParent() {
		RevealRootContentEvent.fire(this, this);
	}
	
	@Override
	protected void onReveal() {
		if (loginStateManager.isAdmin()) {
			getView().revealAdminFunctions(true);
		} else {
			getView().revealAdminFunctions(false);
		}
		
		getView().setUsername(loginStateManager.getCurrentUserName());
		
	}

	@Override
	public void doLogout() {
		UserLoggedOutEvent.fire(this);
		PlaceRequest placeRequest = new PlaceRequest(NameTokens.login);
		placeManager.revealPlace(placeRequest);
		
	}
}
